<?php
defined('EXEC') or die();
$transacao = 'conta_bancaria';

if(!$auth->isRead($transacao)){
	Util::info(Config::AUTH_MESSAGE);
	return true;
}
//Importando a classes
Loader::import('com.atitudeweb.SQL');
$form 			= false;
$rowEdit 		= array();
$table 			= 'tethys.tb_contabancaria';
$tablepk 		= 'ci_contabancaria';
$limitPagina 	= 10; //Registros por página
$faixa 			= 10; //Faixa de páginas que irão ser mostradas paginação (google)
$dif 			= 5; //A diferença que a faixa de páginas irão começar a caminhar (google)
$p 				= (@$_GET['p'] ? $_GET['p'] : 1);
//Exclusão de vários ou um registro
if(isset($_POST['checkdel'])){
	if($auth->isDelete($transacao)){
		if(SQL::remove($table, $tablepk, $_POST['checkdel'])){
			Util::notice('Grupo de Item', 'Excluído com sucesso!');
		}
		else{
			Util::notice('Grupo de Item', 'Houve um erro ao excluir!', 'error');
		}
	}
	else{
		Util::info(Config::AUTH_MESSAGE);
	}
}
//Alteração ou inclusão de um registro
if(isset($_GET['db']) && isset($_GET['form'])){
	$nr_agencia="'".$_POST['nr_agencia']."'";
	$nr_conta="'".$_POST['nr_conta']."'";
	$tp_conta="'".$_POST['tp_conta']."'";
	$ds_banco="'".$_POST['ds_banco']."'";
	$cd_codbanco="'".$_POST['cd_codbanco']."'";
	$saldo_inicial="'".$_POST['saldo_inicial']."'";
	$ds_banco="'".$_POST['ds_banco']."'";
	$fl_ativo = @$_POST['fl_ativo'];
	if (empty($fl_ativo)){
		$fl_ativo= "'N'";
	}else{
		$fl_ativo= "'".$fl_ativo."'";
	}
	$nm_usuario = "'".strtoupper($user['nm_login'])."'";

	if($_GET['db'] == 1 && $_GET['form'] == 0){
		$sql = 'insert into tethys.tb_contabancaria (nr_agencia, nr_conta,tp_conta,ds_banco,cd_codbanco,saldo_inicial,usr_cadastro,fl_ativo,dt_cadastro)
		values ('.$nr_agencia.','.$nr_conta.',UPPER('.$tp_conta.'),UPPER('.$ds_banco.'),'.$cd_codbanco.','.$saldo_inicial.','.$nm_usuario.','.$fl_ativo.',now());';		

	}elseif($_GET['db'] == 1 && $_GET['form'] > 0){
		$sql=" update $table set
		tp_conta=$tp_conta,
		cd_codbanco=$cd_codbanco,
		fl_ativo=$fl_ativo where $tablepk=".$_GET['form'];
	}

	//echo $sql;
	//die;
	if(execute($sql)){
		Controller::setInfo('Conta Bancária', 'Salva com sucesso!', 'success', 'info-circle', 3500);
		Controller::redirect(Util::setLink(array('form=null', 'db=null')));
	}
	else{
		Controller::setInfo('Conta Bancária', 'Por favor contate o administrador.', 'danger', '', 3500);
	}


}
//Mudança do formulário para adição ou alteração de registro
if(isset($_GET['form'])){
	if($_GET['form'] == 0){
		$btFormLabel = 'Adicionar';
	}
	else{
		$btFormLabel = 'Salvar';
		$rowEdit =  query("select * from $table where $tablepk = ".$_GET['form'])->fetch();
	}
	$form = true;
}
//Consulta no banco e mecânica de paginação
if(isset($_POST['search1']) || !$form){
	if(isset($_POST['search1'])){
		$term = addslashes($_POST['search1']);
		$where =  " where ds_banco ilike '%{$term}%'   ";
	}
	else{
		$where =" where 1=1 ";
	}
	$sql=" select * from $table $where order by $tablepk asc limit {$limitPagina} offset ".(($p - 1) * $limitPagina);
	$sqlc=" select count(*) as num from $table $where ";
	$query = query($sql);
	$rowNum = query($sqlc)->fetch();
	$registros = $rowNum['num'];
	$paginacao = Util::pagination($registros, 4);
}

?>
<h3>
	<i class="glyphicon glyphicon-user"></i> Conta Bancária -
	<?php echo (!isset($_GET['form']) ? 'Pesquisa' : (@$_GET['form'] > 0 ? 'Edição' : 'Cadastro')); ?>
</h3>
	<?php if(!isset($_GET['form'])){ ?>
<a href="<?php echo Util::setLink(array('form=0')); ?>"
	class="command-page"><span class="fa fa-plus-square"></span> Novo</a>
	<?php } else{ ?>
<a href="#" class="command-page"
	onclick="window.location='?page=cadastros/conta_bancaria';"><span
	class="fa fa-reply"></span> Voltar</a>
	<?php } ?>

<div class="panel panel-default">
	<div class="panel-body">
		<div id="alerts"></div>
		<?php if(!isset($_GET['form'])){ ?>
		<form action="<?php echo Util::setLink(array('p=null')); ?>"
			method="post" class="form">
			<div class="row">
				<div class="col-md-8">
					<div class="form-group">
						<label class="control-label">Contas Bancárias</label> <input
							type="text" name="search1" id="search1"
							value="<?php echo @$_POST['search1']; ?>" class="form-control" />
					</div>
				</div>
				<div class="col-md-2">
					<div class="form-group">
						<button id="btSearch" class="btn btn-default btn-adjust">
							<span class="fa fa-search"></span> Consultar
						</button>
					</div>
				</div>
			</div>
		</form>
		<!-- LISTAGEM DOS REGISTROS -->
		<form method="post" id="formSearch">
			<div class="table-responsive">
				<table
					class="table table-striped table-bordered table-hover table-condensed">
					<thead>
						<tr class="ui-widget-header">
							<th width="25" class="check"><input type="checkbox"
								id="btCheckAll" /></th>
							<th>Agencia</th>
							<th>Conta</th>
							<th>Banco</th>
							<th>Codigo</th>
							<th>Saldo Inicial</th>
							<th>Saldo Atual</th>
							<th></th>
						</tr>
					</thead>
					<tbody>
					<?php
					$count = 0;
					while($row = $query->fetch()){
						echo '<tr>
					            	<td class="check"><input type="checkbox" class="btCheck" name="checkdel[]"  value="'.$row[$tablepk].'"/></td>
					                <td>'.$row['nr_agencia'].'</td>
					                <td>'.$row['nr_conta'].'</td>
					                <td>'.$row['ds_banco'].'</td>
					                <td>'.$row['cd_codbanco'].'</td>
					                <td>'.$row['saldo_inicial'].'</td>
					                <td>'.$row['saldo_atual'].'</td>
					                <td width="30" align="center">
 					                	<button type="button" onclick="window.location=\''.Util::setLink(array('form='.$row[$tablepk], 'del=null')).'\';" class="btn btn-default btn-xs" title="Editar" data-toggle="tooltip">
									    	<span class="fa fa-pencil"></span>
									    </button>
					                </td>
					        	</tr>';
						$count++;
					}
					?>
					</tbody>
				</table>
			</div>
		</form>
		<!-- FIM FORMULÁRIO PESQUISA -->
		<button id="btDel" class="btn btn-default"
			title="Excluir selecionados" data-toggle="modal"
			data-target="#modalExcluir">
			<span class="fa fa-trash"></span> Excluir
		</button>
		<?php echo $paginacao; ?>
		<?php } else {?>
		<!-- INICIO FORMULÁRIO CADASTRO -->
		<form action="<?php echo Util::setLink(array('db=1')) ?>" class="form"
			method="post" id="formInsertEdit" onsubmit="return test();">
			<fieldset>
				<legend>
					<b>DADOS GERAIS</b>
				</legend>
				<div class="row" id="cadastro_2">
					<div class="col-md-2">
						<div class="form-group">
							<label class="control-label">Agencia:<span class="text-danger">*</span>
							</label> <input type="text" id="nr_agencia" name="nr_agencia"
								value="<?php echo trim(@$rowEdit['nr_agencia']); ?>"
								class="form-control" size="25" />
						</div>
					</div>
					<div class="col-md-2">
						<div class="form-group">
							<label class="control-label">Conta:<span class="text-danger">*</span>
							</label> <input type="text" id="nr_conta" name="nr_conta"
								value="<?php echo trim(@$rowEdit['nr_conta']); ?>"
								class="form-control" size="25" />
						</div>
					</div>
				</div>
				<div class="row" id="cadastro_2">
					<div class="col-md-2">
						<div class="form-group">
							<label class="control-label">Tipo da Conta:<span
								class="text-danger">*</span> </label> <SELECT
								class="form-control" id="tp_conta" name="tp_conta">
								<OPTION value="COR"
								<?php if(@$rowEdit['tp_conta'] == 'COR'){echo "selected='selected'";} ?>>CORRENTE</OPTION>
								<OPTION value="POU"
								<?php if(@$rowEdit['tp_conta'] == "POU"){echo "selected='selected'";} ?>>POUPAN&Ccedil;A</OPTION>
								<OPTION value="CCP"
								<?php if(@$rowEdit['tp_conta'] == 'CCP'){echo "selected='selected'";} ?>>CORRENTE/POUPAN&Ccedil;A</OPTION>
							</SELECT>
						</div>
					</div>

					<div class="col-md-2">
						<div class="form-group">
							<label class="control-label">Banco:<span class="text-danger">*</span>
							</label> <input type="text" id="ds_banco" name="ds_banco"
								value="<?php echo trim(@$rowEdit['ds_banco']); ?>"
								class="form-control" size="25" />
						</div>
					</div>
				</div>
				<div class="row" id="cadastro_2">
					<div class="col-md-2">
						<div class="form-group">
							<label class="control-label">Codigo:<span class="text-danger">*</span>
							</label> <input type="text" id="cd_codbanco" name="cd_codbanco"
								value="<?php echo trim(@$rowEdit['cd_codbanco']); ?>"
								class="form-control" size="25" />
						</div>
					</div>

					<div class="col-md-2">
						<div class="form-group">
							<label class="control-label">Saldo Inicial:<span
								class="text-danger">*</span> </label> <input type="text"
								id="saldo_inicial" name="saldo_inicial"
								value="<?php echo trim(@$rowEdit['saldo_inicial']); ?>"
								class="form-control" size="25" />
						</div>
					</div>
				</div>
				<div class="row" id="cadastro_2">
					<div class="col-md-2">
						<div class="form-group">
							<label class="control-label">Ativo:<span class="text-danger">*</span>
							</label> <input type="checkbox" id="fl_ativo" name="fl_ativo"
								value="S" class="btCheck" size="25"
								<?php if(@$rowEdit['fl_ativo'] == 'S'){echo "checked='checked'";} ?> />
						</div>
					</div>
				</div>
			</fieldset>
			<br clear="all">
			<button id="btInsertEdit" class="btn btn-default" type="submit">
				<span class="fa fa-floppy-o"></span> Salvar
			</button>
		</form>
		<!-- FIM FORMULÁRIO CADASTRO-->
		<?php } ?>
	</div>
</div>

<script type="text/javascript">
$(function(){

	$("#ds_banco").keyup(function(){
		$(this).val($(this).val().toUpperCase());
	    var varString = $(this).val();
	    var stringAcentos = ('àâêôûãõáéíóúçüÀÂÊÔÛÃÕÁÉÍÓÚÇÜ');
	    var stringSemAcento = ('aaeouaoaeioucuAAEOUAOAEIOUCU');
	    var i = new Number();
	    var j = new Number();
	    var cString = new String();
	    var varRes = '';
	    for (i = 0; i < varString.length; i++) {
	        cString = varString.substring(i, i + 1);
	        for (j = 0; j < stringAcentos.length; j++) {
	            if (stringAcentos.substring(j, j + 1) == cString){
	                cString = stringSemAcento.substring(j, j + 1);
	            }
	        }
	        varRes += cString;        

	    }

	    varRes = varRes.replace( /\s/g, '' );

	});

});

</script>

